package cn.itcast.flux.web;

import cn.itcast.flux.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author 虎哥
 */
@Slf4j
@RestController
@RequestMapping("hello")
public class HelloController {

    @GetMapping("sync")
    public User getUserSync(){
        log.warn("sync开始查询用户");
        User user = queryUserById();
        log.warn("sync查询用户结束");
        return user;
    }

    @GetMapping("mono")
    public Mono<User> getUserMono(){
        log.warn("mono开始查询用户");
        Mono<User> mono = Mono.fromSupplier(this::queryUserById);
        log.warn("mono查询用户结束");
        return mono;
    }

    @GetMapping("flux")
    public Flux<User> getFluxUser(){
        log.warn("flux开始查询用户");
        Flux<User> userFlux = createUserFlux();
        log.warn("flux查询用户结束");
        return userFlux;
    }

    @GetMapping(value = "stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getFluxStream(){
        log.warn("stream开始查询用户");
        Flux<User> userFlux = createUserFlux();
        log.warn("stream查询用户结束");
        return userFlux;
    }

    public Flux<User> createUserFlux(){
        // 每隔一秒生成一个用户，总共生成3个用户
        return Flux.interval(Duration.ofSeconds(1))
                .map(Long::intValue)
                .map(i -> User.of("user_" + i, 20 + i))
                ;
    }

    public User queryUserById(){
        User user = User.of("Jack", 21);
        // 模拟任务的耗时
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return user;
    }
}
